package com.ruoyi.web.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.stuxuhai.jpinyin.ChineseHelper;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.PoetryMapper;
import com.ruoyi.web.controller.tool.LocalJSONFileUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/poerty")
public class chinesePoertyController {
    @Autowired
    private PoetryMapper poetryMapper;

    @GetMapping("/sync")
    private void syncJson() throws IOException, PinyinException, InterruptedException {
        Integer total = poetryMapper.total();
        for (int i = 0; i < total; i++) {
            convertzi();
            int anInt = RandomUtil.randomInt(100, 2000);
            Thread.sleep(anInt);
        }

    }


    private void ConvertPoetry() {
        List<Poetry> poetryList = poetryMapper.findPoetryList();
        for (Poetry pp : poetryList) {
            String titletmp = "";
            for (int i = 0; i < pp.getTitle().length(); i++) {
                if (ChineseHelper.isChinese(pp.getTitle().charAt(i))) {
                    titletmp = titletmp + findNewWord(String.valueOf(pp.getTitle().charAt(i)));
                } else titletmp = titletmp + pp.getTitle().charAt(i);
            }
            pp.setTitle(titletmp);

            String contenttmp = "";
            for (int i = 0; i < pp.getContent().length(); i++) {
                if (ChineseHelper.isChinese(pp.getContent().charAt(i))) {
                    contenttmp = contenttmp + findNewWord(String.valueOf(pp.getContent().charAt(i)));
                } else {
                    contenttmp = contenttmp + pp.getContent().charAt(i);
                }
            }
            pp.setContent(contenttmp);

            String authortmp = "";
            for (int i = 0; i < pp.getAuthor().length(); i++) {
                if (ChineseHelper.isChinese(pp.getAuthor().charAt(i))) {
                    authortmp = authortmp + findNewWord(String.valueOf(pp.getAuthor().charAt(i)));
                } else {
                    authortmp = authortmp + pp.getAuthor().charAt(i);
                }
            }
            pp.setAuthor(authortmp);
            System.out.println(pp);
            poetryMapper.updatePoetry(pp.getId(), pp.getTitle(), pp.getContent(), pp.getAuthor());
        }
    }

    private void convertPoetryAuthor(){
        List<PoetryAuthor> poetryAuthor = poetryMapper.findPoetryAuthor();
        for (PoetryAuthor pp : poetryAuthor){
            String nametmp = "";
            for (int i = 0 ; i <pp.getName().length();i++){
                if (ChineseHelper.isChinese(pp.getName().charAt(i))){
                    nametmp = nametmp + ChineseHelper.convertToSimplifiedChinese(pp.getName().charAt(i));
                }else {
                    nametmp = nametmp + pp.getName().charAt(i);
                }
            }
            pp.setName(nametmp);

            String introtmp = "";
            for (int i = 0; i < pp.getIntro().length();i++){
                if (ChineseHelper.isChinese(pp.getIntro().charAt(i))){
                    introtmp = introtmp + ChineseHelper.convertToSimplifiedChinese(pp.getIntro().charAt(i));
                }else {
                    introtmp = introtmp + pp.getIntro().charAt(i);
                }
            }
            pp.setIntro(introtmp);
            System.out.println(pp);
            poetryMapper.updatePoetryAuthor(pp.getId(), pp.getName(), pp.getIntro());
        }
    }

    private void convertlunyu(){
        List<Lunyu> lunyuList = poetryMapper.lunyuList();
        for (Lunyu yu:lunyuList){
            String chaptertmp = "";
            for (int i = 0 ; i < yu.getChapter().length();i++){
                if (ChineseHelper.isChinese(yu.getChapter().charAt(i))){
                    chaptertmp = chaptertmp + ChineseHelper.convertToSimplifiedChinese(yu.getChapter().charAt(i));
                }else {
                    chaptertmp = chaptertmp + yu.getChapter().charAt(i);
                }
            }
            yu.setChapter(chaptertmp);

            String contenttmp = "";
            for (int i = 0 ; i < yu.getContent().length();i++){
                if (ChineseHelper.isChinese(yu.getContent().charAt(i))){
                    contenttmp = contenttmp + ChineseHelper.convertToSimplifiedChinese(yu.getContent().charAt(i));
                }else {
                    contenttmp = contenttmp + yu.getContent().charAt(i);
                }
            }
            yu.setContent(contenttmp);
            System.out.println(yu);
            poetryMapper.updatelunyu(yu.getId(),yu.getChapter(),yu.getContent());
        }

    }

    private void word() throws PinyinException, IOException {
        String filepath = this.getClass().getClassLoader().getResource("data/word.json").getPath();
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        String laster = "";
        while ((tempString = reader.readLine()) != null){
            laster += tempString;
        }
        reader.close();

        cn.hutool.json.JSONArray objects = JSONUtil.parseArray(laster);
        List<Words> ts = JSONUtil.toList(objects, Words.class);
        for (Words tsc : ts) {
            try {
                poetryMapper.insertword(tsc.getWord(),tsc.getOldword(),tsc.getStrokes(),tsc.getPinyin(),tsc.getRadicals(),tsc.getExplanation(),tsc.getMore());
            }catch (Exception e){

            }
        }
    }

    private void chengyu() throws PinyinException, IOException {
        String filepath = this.getClass().getClassLoader().getResource("data/idiom.json").getPath();
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        String laster = "";
        while ((tempString = reader.readLine()) != null){
            laster += tempString;
        }
        reader.close();

        cn.hutool.json.JSONArray objects = JSONUtil.parseArray(laster);
        List<ChengYu> ts = JSONUtil.toList(objects, ChengYu.class);
        for (ChengYu tsc : ts) {
            try {
                poetryMapper.insertChengyu(tsc.getDerivation(),tsc.getExample(),tsc.getExplanation(),tsc.getPinyin(),tsc.getWord(),tsc.getAbbreviation());
            }catch (Exception e){

            }
        }
    }

    private void ci() throws PinyinException, IOException {
        String filepath = this.getClass().getClassLoader().getResource("data/ci.json").getPath();
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        String laster = "";
        while ((tempString = reader.readLine()) != null){
            laster += tempString;
        }
        reader.close();

        cn.hutool.json.JSONArray objects = JSONUtil.parseArray(laster);
        List<Ciyu> ts = JSONUtil.toList(objects, Ciyu.class);
        for (Ciyu tsc : ts) {
            String newci="";
            String newciyb="";
            String newexplanation = "";
            String newexplanationyb = "";

            //判断标题
            for (int i = 0; i <tsc.getCi().length();i++ ){
                String simp = ",";
                if (ChineseHelper.isChinese(tsc.getCi().charAt(i))){
                    try {
                        char simplifiedChinese = ChineseHelper.convertToSimplifiedChinese(tsc.getCi().charAt(i));
                        simp = String.valueOf(simplifiedChinese);
                    }catch (Exception e){
                    }
                }else {
                    simp = String.valueOf(tsc.getCi().charAt(i));
                }
                newci = newci + simp;

            }
            newciyb = PinyinHelper.convertToPinyinString(newci,",", PinyinFormat.WITH_TONE_MARK);
            //内容
            for (int i = 0; i < tsc.getExplanation().length(); i++) {
                String simps = ",";
                if (ChineseHelper.isChinese(tsc.getExplanation().charAt(i))){
                    try {
                        char simplifiedChinese = ChineseHelper.convertToSimplifiedChinese(tsc.getExplanation().charAt(i));
                        simps = String.valueOf(simplifiedChinese);
                    }catch (Exception e){
                    }
                }else {
                    simps = String.valueOf(tsc.getExplanation().charAt(i));
                }
                newexplanation = newexplanation + simps;
            }
            newexplanationyb = PinyinHelper.convertToPinyinString(newexplanation,",", PinyinFormat.WITH_TONE_MARK);
            try {
                poetryMapper.insertCi(newci, newexplanation, newciyb, newexplanationyb);
            }catch (Exception e){

            }
        }
    }

    private void xiehouyu() throws PinyinException, IOException {
        String filepath = this.getClass().getClassLoader().getResource("data/xiehouyu.json").getPath();
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        String laster = "";
        while ((tempString = reader.readLine()) != null){
            laster += tempString;
        }
        reader.close();

        cn.hutool.json.JSONArray objects = JSONUtil.parseArray(laster);
        List<Xiehouyu> ts = JSONUtil.toList(objects, Xiehouyu.class);
        for (Xiehouyu tsc : ts) {
            String newci="";
            String newciyb="";
            String newexplanation = "";
            String newexplanationyb = "";

            //判断标题
            for (int i = 0; i <tsc.getRiddle().length();i++ ){
                String simp = ",";
                if (ChineseHelper.isChinese(tsc.getRiddle().charAt(i))){
                    try {
                        char simplifiedChinese = ChineseHelper.convertToSimplifiedChinese(tsc.getRiddle().charAt(i));
                        simp = String.valueOf(simplifiedChinese);
                    }catch (Exception e){
                    }
                }else {
                    simp = String.valueOf(tsc.getRiddle().charAt(i));
                }
                newci = newci + simp;
            }
            newciyb = PinyinHelper.convertToPinyinString(newci,",", PinyinFormat.WITH_TONE_MARK);
            //内容
            for (int i = 0; i < tsc.getAnswer().length(); i++) {
                String simps = ",";
                if (ChineseHelper.isChinese(tsc.getAnswer().charAt(i))){
                    try {
                        char simplifiedChinese = ChineseHelper.convertToSimplifiedChinese(tsc.getAnswer().charAt(i));
                        simps = String.valueOf(simplifiedChinese);
                    }catch (Exception e){
                    }
                }else {
                    simps = String.valueOf(tsc.getAnswer().charAt(i));
                }
                newexplanation = newexplanation + simps;

            }
            newexplanationyb = PinyinHelper.convertToPinyinString(newexplanation,",", PinyinFormat.WITH_TONE_MARK);
            try {
                poetryMapper.insertxiehouyu(newci, newexplanation, newciyb, newexplanationyb);
            }catch (Exception e){

            }
        }
    }

    private void convert() throws IOException {
        String filepath = this.getClass().getClassLoader().getResource("data/STCharacters.txt").getPath();
        InputStreamReader read = new InputStreamReader(new FileInputStream(filepath), "UTF-8");
        String lineTXT = null;
        BufferedReader bufferedReader = new BufferedReader(read);
        while ((lineTXT = bufferedReader.readLine()) != null) {
            String trim = lineTXT.toString();
                System.out.println("=====");
                ConvertWord word = new ConvertWord();
                if (trim.length()==3){
                    word.setWord(StrUtil.sub(trim,0,1));
                    word.setOldword(StrUtil.sub(trim,-1,trim.length()));
                }else if (trim.length() == 4){
                    word.setWord(StrUtil.sub(trim,0,2));
                    word.setOldword(StrUtil.sub(trim,trim.length()-1,trim.length()));
                } else if (trim.length() == 5) {
                    word.setWord(StrUtil.sub(trim,0,2));
                    word.setOldword(StrUtil.sub(trim,trim.length()-2,trim.length()));
                }
            System.out.println(word);
            System.out.println(trim);
            try {
                poetryMapper.saveWord(word.getWord(),word.getOldword());
            }catch (Exception e){

            }

            System.out.println("=====");

        }

        read.close();
    }

    private String findNewWord(String oldword){
        String word = poetryMapper.findWord(oldword);
        if (StrUtil.isNotEmpty(word)){
            return word;
        }
        return oldword;
    }

    private void JsoupHtml() throws IOException, InterruptedException {
//        Document document = Jsoup.connect("https://www.zdic.net/zd/bs/").get();
//        Elements table = document.select("table");
        Bssy bssy = new Bssy();
        Document document = Jsoup.connect("https://www.zdic.net/zd/py/").get();
        Elements pck = document.getElementsByClass("pck");
        for (Element item:pck ){
            if (!ChineseHelper.isChinese(item.text().charAt(0))) {
                String ziUrl = "https://www.zdic.net/zd/py/py/?py="+item.text();
                Document document1 = refGet(ziUrl);
                Elements tags = document1.getElementsByTag("A");
                for (Element tag :tags){
                    if (StrUtil.isNotEmpty(tag.text())){
//                        System.out.println(item.text());
//                        System.out.println(tag.text());
                        bssy.setZi(tag.text());
                        bssy.setPy(item.text());
                        //获取单个字的
                        String newurl = "https://www.zdic.net/hans/"+tag.text();
                       // Document ziDoc = refGet(newurl);

/*

                        List<String> cy = new ArrayList<>();
                        Elements crefe = ziDoc.getElementsByClass("crefe");
                        for (Element q :crefe){
                           // System.out.println(q.text());
                            cy.add(q.text());
                        }
                        bssy.setCy(JSONUtil.toJsonStr(cy));


                        Set<String> sqljjs = new HashSet<>();
                        Elements js = ziDoc.getElementsByClass("content definitions xnr");
                        for (Element j : js){
                            Elements ol = j.getElementsByTag("p");
                            for (Element p : ol){
                                Elements span = p.getElementsByTag("span");
                               // System.out.println(p.text());
                                for (Element sp : span) {
                                  //  System.out.println(sp.text());
                                    sqljjs.add(sp.text());
                                    sqljjs.add(p.text());
                                }
                            }
                        }
                        bssy.setJjs(JSONUtil.toJsonStr(sqljjs));

                        List<String> sqljs = new ArrayList<>();
                        Elements jss = ziDoc.getElementsByClass("content definitions jnr");
                        for (Element j : jss){
                            Elements ol = j.getElementsByTag("ol");
                            for (Element p : ol){
                                sqljs.add(p.text());
                               // System.out.println(p.text());
                            }
                        }
                        bssy.setJs(JSONUtil.toJsonStr(sqljs));

                        String sqlbs = "";
                        List<String> sqlbh = new ArrayList<>();
                        Elements zBs2 = ziDoc.getElementsByClass("z_bs2");
                        for (Element zbs:zBs2){
                            Elements zTs3 = zbs.getElementsByClass("z_ts3");
                          //  sqlbh = zTs3.parents().text();
                            Elements pp = zbs.getElementsByTag("p");
                            for (Element p : pp){
                                //System.out.println(p.text());
                                sqlbh.add(p.text());
                            }
                            Elements a = zbs.getElementsByTag("a");
                            for (Element aa:a){
                                //System.out.println(aa.text());
                                //部首
                                sqlbs += aa.text();
                            }
                        }
                        bssy.setBs(sqlbs);
                        bssy.setBh(JSONUtil.toJsonStr(sqlbh));

                        String sqlpy = "";
                        Elements zPy = ziDoc.getElementsByClass("z_py");
                        for (Element py : zPy) {
                            Elements zDSong = py.getElementsByClass("z_d song");
                            for (Element zd : zDSong){
                                sqlpy +=zd.text()+"|";
                               // System.out.println(zd.text());
                            }
                        }
                            bssy.setYb(JSONUtil.toJsonStr(sqlpy));*/

                        try {
                            System.out.println(bssy);
                            poetryMapper.saveZi(bssy);
                        }catch (Exception e){

                            }
                        }
                    int anInt = RandomUtil.randomInt(1000, 2000);
                    Thread.sleep(anInt);
                }
            }
        }
        //遍历部首索引页面

//        for (Element tab : table){
//            String bsyx = tab.getElementsByClass("bsyx").text();
//            System.out.println("笔画"+bsyx);
//            bssy.setBsyx(bsyx);
//            Elements tags = tab.getElementsByClass("pck");
//            //遍历页面中的class="pick"的部分
//            for (Element tag:tags){
//                String url = "https://www.zdic.net/zd/bs/bs/?bs="+tag.attr("title");
//                String bs = tag.text();
//                System.out.println("笔画地址"+url);
//                System.out.println("笔数"+bs);
//                bssy.setBs(bs);
//                //根据url继续爬里面存在的字
//                Document childDoc = Jsoup.connect(url).get();
//                Elements selectA = childDoc.select("A");
//                try {
//                    for(int i =1 ;;i++){
//                        url = url +"|"+i;
//                        Document newUrlJsoup = Jsoup.connect(url).get();
//                        selectA.addAll(newUrlJsoup.select("A"));
//                    }
//                }catch (Exception e){
//
//                }
//                for (Element a : selectA){
//                    String zi = a.text();
//                    String ziUrl = a.attr("href");
//                    String ziImg = "";
//                    try {
//                        ziImg=  a.child(0).getElementsByTag("img").attr("src");
//                    }catch (Exception e){
//                    }
//                    System.out.println("字"+zi);
//                    bssy.setZi(zi);
//                    System.out.println("地址"+ziUrl);
//                    System.out.println("图字"+ziImg);
//                    bssy.setImgurl(ziImg);
//                    try {
////                        Document ziDoc = Jsoup.connect("https://www.zdic.net" + ziUrl).get();
////                        System.out.println("单字地址"+"https://www.zdic.net" + ziUrl);
//                        bssy.setUrl("https://www.zdic.net" + ziUrl);
//                        bssy.setStatus("0");
//                    }catch (Exception e){
//
//                    }
//                    try {
//                        System.out.println(bssy);
//                        poetryMapper.saveZi(bssy);
//                    }catch (Exception e){
//
//                    }
//
//                }
//            }
//        }
//        System.out.println(table);
    }

    private Document refGet(String url) throws IOException {
            try {
                Document document = Jsoup.connect(url).get();
                return document;
            }catch (Exception e){
                return refGet(url);
            }
    }

    private String convertWord(String s,Map<String,String> m){
        if (ChineseHelper.isChinese(s.charAt(0)) && m.get(s) != null) {
            return m.get(s);
        }else return s;
    }



    private void convertzi() throws IOException {
        List<ConvertWord> word = poetryMapper.findConvertWord();
        Map<String,String> changes = word.stream().collect(Collectors.toMap(ConvertWord::getOldword,ConvertWord::getWord, (key1,key2) -> key1));

        Bssy bssy = poetryMapper.findBssy();
        //获取单个字的
        String newurl = "https://www.zdic.net/hans/"+bssy.getZi();
         Document ziDoc = refGet(newurl);
                        List<String> cy = new ArrayList<>();
                        String tmpaa = "";
                        Elements crefe = ziDoc.getElementsByClass("crefe");
                        for (Element p :crefe){
                            for (int i =0; i <p.text().length();++i){
                                   tmpaa += convertWord(String.valueOf(p.text().charAt(i)), changes);
                            }
                           // System.out.println(q.text());
                        }
                         cy.add(tmpaa);
                        bssy.setCy(JSONUtil.toJsonStr(cy));


                        Set<String> sqljjs = new HashSet<>();
                        String tmpa = "";
                         String tmpb = "";
                        Elements js = ziDoc.getElementsByClass("content definitions xnr");
                        for (Element j : js){
                            Elements ol = j.getElementsByTag("p");
                            for (Element p : ol){
                                Elements span = p.getElementsByTag("span");
                               // System.out.println(p.text());
                                for (Element sp : span) {
                                  //  System.out.println(sp.text());
                                    for (int i =0; i <sp.text().length();++i){
                                            tmpa += convertWord(String.valueOf(sp.text().charAt(i)), changes);
                                    }
                                    for (int i =0; i <p.text().length();++i){
                                        tmpb+=  convertWord(String.valueOf(p.text().charAt(i)),changes);
                                    }
                                }
                            }
                        }
                        sqljjs.add(tmpa);
                        sqljjs.add(tmpb);
                        bssy.setJjs(JSONUtil.toJsonStr(sqljjs));

                        String tmpc= "";
                        List<String> sqljs = new ArrayList<>();
                        Elements jss = ziDoc.getElementsByClass("content definitions jnr");
                        for (Element j : jss){
                            Elements ol = j.getElementsByTag("ol");
                            for (Element p : ol){
                                for (int i =0; i <p.text().length();++i){
                                    tmpc+=  convertWord(String.valueOf(p.text().charAt(i)),changes);
                                }
                               // System.out.println(p.text());
                            }
                        }
                        sqljs.add(tmpc);
                        bssy.setJs(JSONUtil.toJsonStr(sqljs));

                        String sqlbs = "";
                        List<String> sqlbh = new ArrayList<>();
                        Elements zBs2 = ziDoc.getElementsByClass("z_bs2");
                        for (Element zbs:zBs2){
                            Elements zTs3 = zbs.getElementsByClass("z_ts3");
                          //  sqlbh = zTs3.parents().text();
                            Elements pp = zbs.getElementsByTag("p");
                            for (Element p : pp){
                                //System.out.println(p.text());
                                sqlbh.add(p.text());
                            }
                            Elements a = zbs.getElementsByTag("a");
                            for (Element aa:a){
                                //System.out.println(aa.text());
                                //部首
                                sqlbs += aa.text();
                            }
                        }
                        bssy.setBs(sqlbs);
                        bssy.setBh(JSONUtil.toJsonStr(sqlbh));

                        String sqlpy = "";
                        Elements zPy = ziDoc.getElementsByClass("z_py");
                        for (Element py : zPy) {
                            Elements zDSong = py.getElementsByClass("z_d song");
                            for (Element zd : zDSong){
                                sqlpy +=zd.text()+"|";
                               // System.out.println(zd.text());
                            }
                        }
                            bssy.setYb(JSONUtil.toJsonStr(sqlpy));

        try {
            System.out.println(bssy);
            poetryMapper.updaueZi(bssy);
        }catch (Exception e){

        }
    }
}
